<template>
  <div class="app-container">
    <el-row class="header">
      <el-button type="primary" :icon="RefreshRight" @click="initTaskDefinitionList()">刷新</el-button>
      <el-button type="success" :icon="DocumentAdd" @click="handleDialogValue()">新增</el-button>
    </el-row>
    
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryForm" class="search-form">
      <el-form-item label="任务名称">
        <el-input v-model="queryForm.name" placeholder="请输入任务名称" clearable/>
      </el-form-item>
      <el-form-item label="任务类型">
        <el-select v-model="queryForm.task_type" placeholder="请选择任务类型" clearable style="width: 200px;">
          <el-option label="周期任务" value="crontab" />
          <el-option label="定时任务" value="interval" />
          <el-option label="时钟任务" value="clock" />
          <el-option label="一次性任务" value="once" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      border
      stripe>
      <el-table-column prop="id" label="任务ID" width="120" align="center"/>
      <el-table-column prop="name" label="任务名称" width="180"/>
      <el-table-column prop="task_type" label="任务类型" width="120" align="center">
        <template v-slot="scope">
          <el-tag size="small" v-if="scope.row.task_type === 'crontab'" 
          type="danger" effect="dark">周期任务</el-tag>
          <el-tag size="small" v-else-if="scope.row.task_type === 'interval'"
          type="success" effect="dark">定时任务</el-tag>
          <el-tag size="small" v-else-if="scope.row.task_type === 'clock'" 
          type="warning" effect="dark">时钟任务</el-tag>
          <el-tag size="small" v-else-if="scope.row.task_type === 'once'" 
          type="info" effect="dark">一次性任务</el-tag>
        </template>
      </el-table-column>
      
      <!-- 周期任务配置 -->
      <el-table-column label="任务配置" width="200">
        <template v-slot="scope">
          <div v-if="scope.row.task_type === 'crontab'">
            <div>分钟: {{ scope.row.crontab_minute || '*' }}</div>
            <div>小时: {{ scope.row.crontab_hour || '*' }}</div>
            <div>星期: {{ scope.row.crontab_day_of_week || '*' }}</div>
            <div>日期: {{ scope.row.crontab_day_of_month || '*' }}</div>
            <div>月份: {{ scope.row.crontab_month_of_year || '*' }}</div>
          </div>
          <div v-else-if="scope.row.task_type === 'interval'">
            <div>执行间隔: {{ scope.row.interval_time }} {{ getIntervalUnitText(scope.row.interval_unit) }}</div>
          </div>
          <div v-else-if="scope.row.task_type === 'clock'">
            <div>执行时间: {{ scope.row.clock_time }}</div>
          </div>
          <div v-else>
            <el-tag type="info" size="small">一次性任务</el-tag>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="description" label="任务描述" />
      <el-table-column prop="tasks_count" label="关联任务数" width="120" align="center"/>
      <el-table-column prop="create_time" label="创建时间" width="180" align="center"/>
      <el-table-column prop="update_time" label="更新时间" width="180" align="center"/>
      <el-table-column prop="creator" label="创建人" width="120" align="center"/>
      <el-table-column prop="modifier" label="修改人" width="120" align="center"/>
      <el-table-column prop="action" label="操作" width="300" fixed="right" align="center">
        <template v-slot="scope">
          <el-button type="primary" :icon="Edit" @click="handleDialogValue(scope.row.id)"/>
          <el-popconfirm title="您确定要删除这条记录吗？" @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" :icon="Delete"/>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页区域 -->
    <el-pagination
      v-model:currentPage="queryForm.page"
      v-model:page-size="queryForm.page_size"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    
    <!-- 对话框组件 -->
    <Dialog 
      v-model="dialogVisible" 
      :dialogVisible="dialogVisible" 
      :id="id" 
      :dialogTitle="dialogTitle" 
      @initTaskDefinitionList="initTaskDefinitionList">
    </Dialog>
  </div>
</template>

<script setup>
import {Search, Delete, DocumentAdd, Edit, RefreshRight} from '@element-plus/icons-vue'
import {ref, reactive} from 'vue'
import requestUtil from "@/util/request"
import Dialog from './components/dialog.vue'
import {ElMessage} from 'element-plus'

// 表格数据
const tableData = ref([])
const total = ref(0)

// 搜索表单
const queryForm = ref({
  name: '',
  task_type: '',
  page: 1,
  page_size: 10
})


// 对话框相关
const id = ref(-1)
const dialogVisible = ref(false)
const dialogTitle = ref('')


// 初始化任务定义列表
const initTaskDefinitionList = async () => {
  try {
    if (queryForm.value.name) {
      queryForm.value.page=1
    }
    const res = await requestUtil.get('tasks/task_definitions/', queryForm.value)
    tableData.value = res.results
    total.value = res.count
  } catch (error) {
    console.error('获取任务定义列表失败', error)
    ElMessage.error('获取任务定义列表失败')
  }
}


// 首次加载数据
initTaskDefinitionList()


// 处理对话框显示
const handleDialogValue = (taskId) => { 
  if (taskId) {
    id.value = taskId
    dialogTitle.value = "任务定义编辑"
  } else {
    id.value = -1
    dialogTitle.value = "任务定义添加"
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (taskId) => {
  try {
    await requestUtil.del("tasks/task_definitions/" + taskId + "/")
    ElMessage.success("删除成功")
    initTaskDefinitionList()
  } catch (error) {
    console.error(error)
    ElMessage.error("删除失败")
  }
}

// 处理搜索
const handleSearch = () => {
  queryForm.value.page = 1
  initTaskDefinitionList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(queryForm.value).forEach(key => {
    queryForm.value[key] = ''
  })
  queryForm.value.page = 1
  initTaskDefinitionList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryForm.value.page_size = val
  initTaskDefinitionList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryForm.value.page = val
  initTaskDefinitionList()
}

// 获取间隔单位文本
const getIntervalUnitText = (unit) => {
  const unitMap = {
    'seconds': '秒',
    'minutes': '分钟',
    'hours': '小时',
    'days': '天'
  }
  return unitMap[unit] || unit
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.header {
  padding-bottom: 16px;
  box-sizing: border-box;
}

.search-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}

.el-pagination {
  float: right;
  padding: 20px 0;
  box-sizing: border-box;
}

::v-deep th.el-table__cell {
  word-break: break-word;
  background-color: #f8f8f9 !important;
  color: #515a6e;
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
